#include "Socket.h"

SOCKET createdSocket;

bool socketConnect() 
{
    WSADATA wsaData;
    int connectionResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (connectionResult != NO_ERROR)
		printf("Client: Error at WSAStartup().\n");
    else
        printf("Client: WSAStartup() has initialized.\n");

	// Create a socket.
    createdSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (createdSocket == INVALID_SOCKET) {
        printf("Client: socket() - Error at socket(): %ld\n", WSAGetLastError());
        WSACleanup();
        return false;
    }
	else
       printf("Client: socket() has been created!\n");

    // Connect to a server.
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    // Just test using the localhost, you can try other IP address
    clientService.sin_addr.s_addr = inet_addr(IPADDRESS);
    clientService.sin_port = htons(PORT);

    if (connect(createdSocket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR) {
        printf("Client: connect() - Failed to connect.\n");
        WSACleanup();
        return false;
    }
    else
       printf("Client has connected to the serve!.\n");

    // Send and receive data.
	printf("Client: Connected!\n");
	return true;
}

void sendMessage(char* s, int len)
{
	int bytesSent = send(createdSocket, s, len, 0);
	if(bytesSent == SOCKET_ERROR)
		printf("Client: send() error %ld.\n", WSAGetLastError());
}

void recieveMessage(char *ans)
{
	int bytesRecv = SOCKET_ERROR;
	int pos = 0;
	while (true) {
		recv(createdSocket, &ans[pos], 1, 0);
		if (ans[pos] == '\n')
			break;
		pos++;
	}
	ans[pos] = 0;
	std::cout << "prolog answered: " << ans << std::endl;
}

void quit() 
{
	std::cout << "Asking prolog to quit" << std::endl;
	char buff[] = "quit.\n";
	sendMessage(buff, 6);
	char ans[128];
	recieveMessage(ans);
}